<template>
  <el-popover
    :visible="notificationStore.showPopover"
    @update:visible="notificationStore.showPopover = $event"
    placement="bottom-end"
    width="350"
    trigger="click"
    teleported
  >
    <template #reference>
      <el-badge :value="notificationStore.unreadCount" class="item" v-if="notificationStore.unreadCount > 0">
        <el-icon style="cursor:pointer; font-size: 28px;">
          <BellFilled />
        </el-icon>
      </el-badge>
      <el-icon v-else style="cursor:pointer; font-size: 28px;">
        <BellFilled />
      </el-icon>
    </template>
    <div style="max-height:300px;overflow:auto;">
      <el-list v-if="notificationStore.notifications.length">
        <el-list-item v-for="item in notificationStore.notifications" :key="item.id">
          <div>
            <b>{{ item.title }}</b>
            <div style="font-size:12px;color:#888;">{{ item.content }}</div>
            <div style="font-size:12px;color:#aaa;">{{ item.createTime }}</div>
          </div>
          <el-button v-if="!item.isRead" size="small" type="primary" @click="markAsRead(item.id)">标记已读</el-button>
        </el-list-item>
      </el-list>
      <div v-else style="text-align:center;color:#aaa;">暂无消息</div>
    </div>
    <div style="text-align:right;margin-top:8px;">
      <el-button type="text" @click="goToCenter">进入消息中心</el-button>
      <el-button type="text" @click="fetchNotifications">刷新</el-button>
    </div>
  </el-popover>
</template>

<script setup>
import { onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { BellFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useNotificationStore } from '@/stores/notification'
import { useUserStore } from '@/stores/user'

const notificationStore = useNotificationStore()
const userStore = useUserStore()
const router = useRouter()

const fetchNotifications = async () => {
  console.log('获取消息列表')
  await notificationStore.fetchUnreadCount()
  await notificationStore.fetchNotifications()
}

const markAsRead = async (id) => {
  try {
    await notificationStore.markAsRead([id])
    ElMessage.success('已标记为已读')
    await fetchNotifications()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const goToCenter = () => {
  router.push('/notifications')
  notificationStore.showPopover = false
}

onMounted(fetchNotifications)
</script>

<style scoped>
</style> 